<template>
  <el-dialog draggable :model-value="open" @close="close" :title="formSetting.name">
    <el-form label-width="auto" v-bind="formSetting.formStyle" :model="formData" ref="ruleFormRef" class="custom-form">
      <FormGroupRender v-for="(field, index) in formSetting.formItemList" :field="field" :data="formData" />
    </el-form>
    <template #footer>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { FormInstance } from 'element-plus';
import successMsg from '@/utils/successMsg';
import { FormField, FormGroup, FormOperateType, FormSetting } from '../..';
const open = defineModel<boolean>();

// 操作类型
const operateType = defineModel<FormOperateType>("operateType");

const formSetting = defineModel<FormSetting>("formSetting");

const ruleFormRef = ref<FormInstance>();

// 表单数据
const data = defineModel<object>("data");

// 提交字段处理
const flag = ref(false);
const formData = computed(() => {
  if (!flag.value) {
    if (operateType.value === 'create' || operateType.value === 'preview') {
      formSetting.value.formItemList.forEach(x => {
        getFormDataField(data.value, x);
      });
    } else if (operateType.value === 'update') {
      formSetting.value.formItemList.forEach(x => {
        convertFormDataField(data.value, x);
      });
    }
    flag.value = true;
  }
  return data.value;
})

const getFormDataField = (obj: any, formItem: FormField) => {
  if (formItem.group === 'form') {
    const field = formItem.field || formItem.id;
    obj[field] = null;
    if (formItem.dataType === 'array') {
      obj[field] = [];
    }
  } else if (formItem.group === 'layout') {
    formItem.formItemList.forEach(x => {
      getFormDataField(obj, x);
    })
  }
}

const convertFormDataField = (obj: any, formItem: FormField) => {
  if (formItem.group === 'form') {
    const field = formItem.field || formItem.id;
    if (formItem.dataType === 'array') {
      obj[field] = JSON.parse(obj[field]);
    }
  } else if (formItem.group === 'layout') {
    formItem.formItemList.forEach(x => {
      convertFormDataField(obj, x);
    })
  }
}

const emits = defineEmits(['submit']);
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (operateType.value === 'preview') {
        successMsg(true, '校验通过')
      } else {
        emits('submit', formData.value);
      }
    } else {
      successMsg(false, '校验失败')
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const close = () => {
  open.value = false;
}
</script>

<style lang="scss" scoped></style>
